import 'dart:async';
import 'dart:io';

import 'package:bike_ride/api/api_defines.dart';
import 'package:bike_ride/common/net/dio_client.dart';
import 'package:bike_ride/common/net/dio_response.dart';
import 'package:bike_ride/common/util/account_manager.dart';
import 'package:bike_ride/common/util/app_utils.dart';
import 'package:bike_ride/common/util/extension.dart';
import 'package:bike_ride/common/util/hysize_fit.dart';
import 'package:bike_ride/common/util/permission_utils.dart';
import 'package:bike_ride/common/widget/dialog/mydialog.dart';
import 'package:bike_ride/model/version/dialog.dart';
import 'package:bike_ride/model/version/model/version_info.dart';
import 'package:bike_ride/model/version/model/version_model.dart';
import 'package:collection/collection.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:install_plugin/install_plugin.dart';
import 'package:mobx/mobx.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:simple_html_css/simple_html_css.dart';
import 'package:url_launcher/url_launcher.dart';

///版本更新
// This is our generated file (we'll see this soon!)
part 'version.g.dart';

// We expose this to be used throughout our project
class Version = _Version with _$Version;

abstract class _Version with Store {
  ///是否需要更新
  @observable
  bool needUpdate = false;
  bool _loading = false;

  @observable
  List<VersionModel> versionList = [];
  final int _pageSize = 10;

  ///当前版本是否落后线上版本
  ///[version]需要和后端比较的版本
  bool isBehindVersion(String? version, String localVersion) {
    if (version != null &&
        version.isNotEmpty) {
      final netVersion = version.split('.').map((e) => int.parse(e)).toList();
      final loVersion = localVersion.split('.').map((e) => int.parse(e)).toList();
      for (var i = 0; i < netVersion.length; i++) {
        if (loVersion.length <= i) {
          return true;
        }
        if (netVersion[i] > loVersion[i]) {
          return true;
        } else if (netVersion[i] < loVersion[i]) {
          return false;
        }
      }
    }
    return false;
  }

  ///版本最新版本
  ///
  /// [forceUpdate]是否忽略版本判断，弹窗提醒下载最新版本
  @action
  Future latest(BuildContext buildContext, {bool feedBack = false,bool forceUpdate = false}) async {
    if (_loading) return;
    _loading = true;
    if (feedBack) {
      EasyLoading.show(status: '检测新版本中', dismissOnTap: true);
    }
    final packageInfo = await PackageInfo.fromPlatform();

    final response = await DioClient().doPost(kAPIURLLatestVersion,
        data: {
          'application_type': 5, //固定
          'agent': Platform.isIOS ? 1 : 2,
          'application_code': AccountManager.brandCode,
          'version': packageInfo.version,
          'isNew': false,
        });
    _loading = false;

    if (response.statusCode == REQUEST_SUCCESS) {
      final version = VersionInfo.fromJson(response.data);

      if (isBehindVersion(version.version, packageInfo.version) || forceUpdate) {
        if (buildContext.mounted) {
          if (version.remoteUrl != null && version.remoteUrl!.isNotEmpty) {
            updateNormalByDialog(
                buildContext, version, packageInfo.version, feedBack, forceUpdate);
          }
        }

        if(!forceUpdate){
          needUpdate = true;
        }
      } else {
        if (feedBack) {
          EasyLoading.showSuccess('已经是最新版本');
        }
      }
    } else {
      if (feedBack) {
        DioClient.showError(response);
      }
    }
  }

  ///版本记录
  @action
  Future logs(int? pageIndex) async {
    final response = await DioClient().doPost(kAPIURLVersionLogs,
        data: {
          'application_type': 5, //固定
          'size': _pageSize,
          'page': pageIndex,
          'application_code': AccountManager.brandCode,
          'agent': Platform.isIOS ? 1 : 2,
          'isNew': false,
        });
    if (response.statusCode == REQUEST_SUCCESS) {
      final list = response.toList().map((e) => VersionModel.fromJson(e)).toList();
      if (pageIndex == 1) {
        versionList =  list;
      } else {
        versionList.addAll(list);
      }
      return versionList;
    } else {
      DioClient.showError(response);
      return [];
    }
  }

  ///仅支持Android 端显示的后台下载说明
  void showTips(BuildContext context) {
    PermissionUtil().handleNotificationPermission().then((status) {
      if (context.mounted) {
        showAlertDialog(
          title: '后台下载说明',
          context: context,
          content: BackgroundDownloadDialogWidget(status: status),
          hasCancel: false,
          confirmName: '我知道了',
          onConfirm: () {
            Navigator.of(context).pop();
          },
        );
      }
    });
  }

  ///提醒更新弹窗 & 强制更新
  updateNormalByDialog(BuildContext context, VersionInfo versionInfo,
      String localVersionStr, bool feedBack,bool forceUpdate) {
    final Histories? forceUpdateItem =
    versionInfo.histories?.firstWhereOrNull((element) {
      if (!isBehindVersion(element.version, localVersionStr)) {
        return false;
      }
      return element.upgradeType == 1;
    });

    if (versionInfo.style == null || versionInfo.style == 0) {
      showDialog(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext bContext) => UpgradeDialog(
          feedBack: feedBack,
          forceUpdate:forceUpdate,
          showTipDialog: () => showTips(context),
          versionModel: versionInfo,
          hasCancel: forceUpdateItem == null,
          valueChanged: (value) async{
            /// iOS value:下载地址url
            /// android value:文件系统地址
            InstallPlugin.install(value, appId: await AppUtils.getAppPackageName())
                .then((result) {
              print('install apk $result');
              String resultStr = result.toString();
              if (resultStr.contains('Install Success')) {
                //这个不提示，需要解决
                resultStr = '安装成功';
              }else{
                if (resultStr.contains('Install Permission Fail')) {
                  resultStr = '请允许应用安装权限，才能安装应用';
                  if(forceUpdateItem != null){
                    updateNormalByDialog(context,versionInfo,localVersionStr,feedBack,forceUpdate);
                  }
                } else if (resultStr.contains('Install Cancel')) {
                  resultStr = '已取消安装';
                  if(forceUpdateItem != null){
                    updateNormalByDialog(context,versionInfo,localVersionStr,feedBack,forceUpdate);
                  }
                }
              }
              EasyLoading.showToast(resultStr,
                  toastPosition: EasyLoadingToastPosition.bottom);
            }).catchError((error) {
              print('install apk error: $error');
              if(forceUpdateItem != null){
                updateNormalByDialog(context,versionInfo,localVersionStr,feedBack,forceUpdate);
              }
              EasyLoading.showToast(error,
                  toastPosition: EasyLoadingToastPosition.bottom);
            });
          },
        ),
      );
    } else {
      showAlertDialog(
        title: versionInfo.title ?? '更新提示',
        context: context,
        content: HTML.toRichText(context, versionInfo.desc ?? ''),
        barrierDismissible: false,
        onWillPopBol: false,
        hasCancel: forceUpdateItem == null,
        //目前还没实现静默安装
        onCancel: () {
          Navigator.of(context).pop();
        },
        cancelName: '暂不更新',
        confirmName: '去更新',
        onConfirm: () {
          if (versionInfo.remoteUrl != null &&
              versionInfo.remoteUrl!.isNotEmpty) {
            launch(versionInfo.remoteUrl!);
          }
        },
      );
    }
  }

}

///后台下载弹窗文字：有状态的，系统通知权限授权后刷新视图的组件
class BackgroundDownloadDialogWidget extends StatefulWidget {
  final PermissionStatus status;

  const BackgroundDownloadDialogWidget({Key? key, required this.status})
      : super(key: key);

  @override
  State<BackgroundDownloadDialogWidget> createState() =>
      _BackgroundDownloadDialogWidgetState();
}

class _BackgroundDownloadDialogWidgetState
    extends State<BackgroundDownloadDialogWidget> {
  late bool granted;
  late Timer timer;

  @override
  void initState() {
    super.initState();
    granted = widget.status == PermissionStatus.granted;
    timer = Timer.periodic(const Duration(seconds: 1), (Timer t) async {
      granted =
          await Permission.notification.status == PermissionStatus.granted;
      setState(() {

      });
    });
  }

  @override
  void dispose() {
    super.dispose();
    timer.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          '已为您切换到后台下载，下载完成后弹窗提醒您安装应用',
          style: TextStyle(
            fontSize: 32.rpx,
            color: Colors.black87,
            fontWeight: FontWeight.w500,
          ),
        ),
        SizedBox(
          height: 10.rpx,
        ),
        Text(
          '1.如何查看下载进度?\n 请先授权应用通知权限后通过下拉系统状态栏查看\n2.下载过程中会影响App正常使用吗?\n 网络正常环境下，不影响',
          textAlign: TextAlign.start,
          style: TextStyle(color: Colors.black87.withOpacity(0.5), fontSize: 28.rpx),
        ),
        SizedBox(
          height: 30.rpx,
        ),
        Row(
          children: [
            Text('应用通知权限状态：',
                style: TextStyle(
                  fontSize: 28.rpx,
                  color: Colors.grey,
                  fontWeight: FontWeight.w500,
                )),
            GestureDetector(
              child: Text(
                granted ? '已授权' : '未授权,前往设置',
                style: TextStyle(
                    color: Theme.of(context).colorScheme.primary.withOpacity(0.7),
                    fontSize: 28.rpx,
                    decoration: TextDecoration.underline),
              ),
              onTap: () {
                if (!granted) {
                  openAppSettings();
                }
              },
            )
          ],
        ),
      ],
    );
  }
}
